package org.example.springhelloshell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

@ShellComponent
public class FileManagerCommands {

    private Path currentDir = Paths.get(System.getProperty("user.dir"));

    @ShellMethod(value = "List files in current directory", key = "ls")
    public String listFiles(@ShellOption(defaultValue = "false") boolean detailed) {
        try {
            if (detailed) {
                return Files.list(currentDir).map(path -> {
                    try {
                        return String.format("%s\t%s\t%s", path.getFileName(), Files.size(path), Files.getLastModifiedTime(path));
                    } catch (IOException e) {
                        return path.getFileName().toString();
                    }
                }).collect(Collectors.joining("\n"));
            } else {
                return Files.list(currentDir).map(path -> path.getFileName().toString()).collect(Collectors.joining("  "));
            }
        } catch (IOException e) {
            return "Error listing files: " + e.getMessage();
        }
    }

    @ShellMethod(value = "Change directory", key = "cd")
    public String changeDirectory(String directory) {
        Path newDir = currentDir.resolve(directory).normalize();
        File file = newDir.toFile();

        if (!file.exists() || !file.isDirectory()) {
            return "Directory does not exist: " + newDir;
        }

        currentDir = newDir;
        return "Current directory: " + currentDir;
    }

    @ShellMethod(value = "Show current directory", key = "pwd")
    public String printWorkingDirectory() {
        return currentDir.toString();
    }

    @ShellMethod(value = "Create a new file", key = "touch")
    public String createFile(String filename) {
        try {
            Path filePath = currentDir.resolve(filename);
            Files.createFile(filePath);
            return "Created file: " + filePath;
        } catch (IOException e) {
            return "Error creating file: " + e.getMessage();
        }
    }

    @ShellMethod(value = "Create a new directory", key = "mkdir")
    public String createDirectory(String dirname) {
        try {
            Path dirPath = currentDir.resolve(dirname);
            Files.createDirectory(dirPath);
            return "Created directory: " + dirPath;
        } catch (IOException e) {
            return "Error creating directory: " + e.getMessage();
        }
    }
}
